package com.nur.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.nur.dal.Conexion;
import com.nur.dto.BackupContenido;

public class BackupContenidoDao extends Dao<BackupContenido>{

	public BackupContenidoDao(Context context) {
		super(context);
	}

	@Override
	public void insertar() throws Exception {
		Conexion conexion = Conexion.getInstance();
		SQLiteDatabase db = conexion.getWritableDatabase();
		
		if(dto == null)
			throw new Exception("El objeto a insertar no puede ser nulo");
		
		ContentValues params = new ContentValues();
		params.put("idbackup", this.dto.getIdBackUp());
		params.put("idnota", this.dto.getIdNota());
		params.put("comentario", this.dto.getComentario());
		params.put("hora_inicio", this.dto.getHoraInicio());
		params.put("hora_fin", this.dto.getHoraFin());
		params.put("tipo", this.dto.getTipo());
		
		db.insert("backupcontenido", null, params);
	}

	@Override
	public void update() throws Exception {
		Conexion conexion = Conexion.getInstance();
		SQLiteDatabase db = conexion.getWritableDatabase();
		
		if(dto == null)
			throw new Exception("El objeto a actualizar no puede ser nulo");
		
		ContentValues params = new ContentValues();
		params.put("idnota", this.dto.getIdNota());
		params.put("comentario", this.dto.getComentario());
		params.put("hora_inicio", this.dto.getHoraInicio());
		params.put("hora_fin", this.dto.getHoraFin());
		params.put("tipo", this.dto.getTipo());

		db.update("backupcontenido", params,"idbackup=?", new String[]{ String.valueOf(this.dto.getIdBackUp()) });
	}

	@Override
	public void delete() throws Exception {
		Conexion conexion = Conexion.getInstance();
		SQLiteDatabase db = conexion.getWritableDatabase();
		
		if(dto == null)
			throw new Exception("El objeto a eliminar no puede ser nulo");
		
		db.delete("backupcontenido", "idbackup=?", new String[]{ String.valueOf(super.dto.getIdBackUp()) });
	}

	@Override
	public BackupContenido select(int id) {
		Conexion conexion = Conexion.getInstance();
		SQLiteDatabase db = conexion.getReadableDatabase();
		
		Cursor cursor = db.rawQuery("SELECT idbackup, "
					+ "idnota, "
					+ "comentario, "
					+ "hora_inicio, "
					+ "hora_fin, "
					+ "fecha, "
					+ "tipo FROM backupcontenido WHERE idbackup = ?", 
				new String[]{ String.valueOf(id) });
		
		if(!cursor.moveToFirst())
			return null;
		
		int idBackup = cursor.getInt(0);
		int idNota = cursor.getInt(1);
		String comentario = cursor.getString(2);
		String horaInicio = cursor.getString(3);
		String horaFin = cursor.getString(4);
		String fecha = cursor.getString(5);
		String tipo = cursor.getString(6);
		boolean esNuevo = cursor.getInt(7) == 1;
		
		BackupContenido objNota = new BackupContenido(idBackup,idNota, comentario, horaInicio, horaFin, fecha, tipo);
		
		return objNota;
	}

}
